package com.ssyc.gsk_teacher.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.lzy.okgo.model.HttpParams;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PickChooseManager;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.MaxTextLengthFilter;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.adapter.ClassGvAdapter;
import com.ssyc.gsk_teacher.adapter.ShowPicGvAdapter;
import com.ssyc.gsk_teacher.adapter.WorkSutdentGvAdapter;
import com.ssyc.gsk_teacher.bean.ClassInfo;
import com.ssyc.gsk_teacher.bean.StudentTel;
import com.ssyc.gsk_teacher.bean.WorkInfo;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;

/**
 * 教师端--布置练习
 * Created by Kevin on 2018/6/27
 */

public class TeacherAssignHomeworkActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    //跟布局
    private LinearLayout llMain;
    //顶部布局
    private LinearLayout rlMain;
    //展示所有学生的GridView
    private MyGridView mgv;
    //展开布局
    private LinearLayout llShow;
    //打开列表
    private TextView tvShow;
    private EditText etLastWork;
    private EditText etNewWork;
    //展示选择图片的GridView
    private MyGridView mgvShowWork;
    //提交
    private TextView tvSave;

    //选择班级
    private TextView lv_class;
    private ImageView lv_record;

    //加载布局
    private RelativeLayout rlLoading;

    //内容布局
    private ScrollView sl_content;

    //提示布局,班级是否有学生
    private TextView tv_msg;

    //上次练习字数
    private TextView tv_last_num;

    //本次练习字数
    private TextView tv_new_num;

    //展示学生信息的数据集合
    private List<WorkInfo.ListBean> oldDatas;

    // 初次从服务器请求的学生的全部数据
    private List<WorkInfo.ListBean> newDatas;

    //填充适配器的图片地址
    private List<String> mPicPaths;

    //展示学生列表的适配器
    private WorkSutdentGvAdapter workSutdentGvAdapter;

    //适配对象
    private ShowPicGvAdapter adapter;

    // 上次点评的练习情况
    private String lastContent;

    // 布置的本次练习
    private String newContent;
    private ImageView lvBackTop;
    private RelativeLayout rlBackTop;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //标题栏的布局
    private LinearLayout llTitle;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //Handler对象
    private Handler handler = new Handler();


    // 初次从服务器请求的学生的全部数据
    private List<StudentTel> stuList;

    //班级ID
    private String userclass;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_assign_homework;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //设置监听
        initListener();

        //设置展示学生列表的GridView
        initGv();

        //请求服务器
        httpMethod();
    }

    /**
     * 设置输入框的长度监听
     */
    private void initListener() {
        etLastWork.setFilters(new InputFilter[]{new MaxTextLengthFilter(501)});
        etNewWork.setFilters(new InputFilter[]{new MaxTextLengthFilter(501)});

        //输入框的改变监听
        etLastWork.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etLastWork.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tv_last_num.setText("0/500");
                } else {
                    if (inputText.length() > 501) {
                        tv_last_num.setText("500/500");
                    } else {
                        tv_last_num.setText(inputText.length() + "/500");
                    }
                }
            }
        });
        etNewWork.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etNewWork.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tv_new_num.setText("0/500");
                } else {
                    if (inputText.length() > 501) {
                        tv_new_num.setText("500/500");
                    } else {
                        tv_new_num.setText(inputText.length() + "/500");
                    }
                }
            }
        });
    }

    /**
     * 初始化视图的方法
     */
    @SuppressLint("ClickableViewAccessibility")
    public void initView() {
        lvBackTop = findViewById(R.id.lv_back_top);
        rlBackTop = findViewById(R.id.rl_back_top);
        rlBackTop.setOnClickListener(this);
        lv_class = findViewById(R.id.lv_class);
        lv_class.setOnClickListener(this);
        lv_record = findViewById(R.id.lv_record);
        lv_record.setVisibility(View.INVISIBLE);
        lv_record.setOnClickListener(this);
        rlMain = findViewById(R.id.ll_title);
        mgv = findViewById(R.id.mgv);
        tvShow = findViewById(R.id.tv_show);
        tvShow.setOnClickListener(this);
        llShow = findViewById(R.id.ll_show);
        etLastWork = findViewById(R.id.et_last_work);
        etNewWork = findViewById(R.id.et_new_work);
        mgvShowWork = findViewById(R.id.mgvShowWork);
        tvSave = findViewById(R.id.tv_save);
        tvSave.setOnClickListener(this);
        llMain = findViewById(R.id.ll_main);
        //标题栏
        llTitle = findViewById(R.id.ll_title);
        rlLoading = findViewById(R.id.rl_loading);
        sl_content = findViewById(R.id.sl_content);
        sl_content.setVisibility(View.GONE);
        rlLoading.setVisibility(View.VISIBLE);
        tv_msg = findViewById(R.id.tv_msg);
        tv_msg.setVisibility(View.GONE);

        tv_last_num = findViewById(R.id.tv_last_num);
        tv_new_num = findViewById(R.id.tv_new_num);

        //设置输入框的触摸事件监听
        etLastWork.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /*告诉父组件不要拦截他的触摸事件*/
                v.getParent().requestDisallowInterceptTouchEvent(true);
                if (MotionEvent.ACTION_UP == event.getAction()) {
                    /*告诉父组件可以拦截他的触摸事件*/
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }

                return false;
            }
        });
        etNewWork.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /*告诉父组件不要拦截他的触摸事件*/
                v.getParent().requestDisallowInterceptTouchEvent(true);
                if (MotionEvent.ACTION_UP == event.getAction()) {
                    /*告诉父组件可以拦截他的触摸事件*/
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }

                return false;
            }
        });
    }


    /**
     * 请求服务器获取数据
     */
    private void httpMethod() {

        //请求服务器数据获取班级列表
        httpClass();

        //初始化选择相册
        initGvShowPic();
    }


    /**
     * 获取班级列表的数据
     */
    private void httpClass() {

        newDatas = new ArrayList<>();

        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("c", AccountUtils.getAccount(this));
        map.put("user_type", SPUtil.getString(this, SpKeys.USERTYPE));
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.GETCLASS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
                if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }

                ClassInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ClassInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if (null != info) {
                    if ("1".equals(info.getStatus())) {
                        //返回成功
                        classInfos = info.getList();
                        if (null != classInfos && classInfos.size() != 0) {
                            //有数据
//                            if (null != sl_content && sl_content.getVisibility() != View.VISIBLE) {
//                                sl_content.setVisibility(View.VISIBLE);
//                            }

                            //加载完班级列表数据后并且设置好列表展示数据后标题栏选择班级弹框可以进行点击了
                            isLoadClassCompleted = true;

                            userclass = classInfos.get(0).getClassnum();

                            //默认加载第一个班级的数据
                            initMgv(userclass);

                        } else {
//                            UiUtils.Toast("没有班级数据", false);
                            sl_content.setVisibility(View.GONE);
                            lv_class.setVisibility(View.INVISIBLE);
                            lv_record.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getStatus(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getStatus());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }

    /**
     * 弹窗
     */
    private void onChoiceClass() {

        if (null == classInfos || classInfos.size() == 0) {
            //证明没有班级列表数据,不做任何操作
            return;
        } else {

            PopUpManager.showPop(this, R.layout.teacher_pop_class, 0.3f, llTitle, new PopUpManager.onGetViewListener() {
                @Override
                public void getChildView(View view, int layoutResId) {
                    //展示班级列表的GridView
                    MyGridView gv = view.findViewById(R.id.gv);

                    //第一步:设置默认的选中状态的班级位置
                    syncClassGvState();

                    //第二步:设置列表数据
                    classGvAdapter = new ClassGvAdapter(TeacherAssignHomeworkActivity.this,
                            classInfos, R.layout.teacher_gv_class);
                    gv.setAdapter(classGvAdapter);

                    //第三步:设置点击事件
                    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                            //记录选中的位置
                            popSelectedPos = pos;

                            //同步GridView的状态,设置列表的选中状态
                            syncClassGvState();

                            //通知适配器刷新
                            classGvAdapter.notifyDataSetChanged();

                            //根据当前选中的班级去请求班级小组的数据
                            initMgv(classInfos.get(pos).getClassnum());

                            //记录当前选择的班级号
                            userclass = classInfos.get(pos).getClassnum();

                            //延迟关闭弹框
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    PopUpManager.dismiss();
                                }
                            }, 100);
                        }
                    });
                }
            });
        }
    }


    /**
     * 同步班级列表GridView的选中和没选中的状态
     */
    private void syncClassGvState() {
        for (int i = 0; i < classInfos.size(); i++) {
            if (popSelectedPos == i) {
                classInfos.get(i).setSelected(true);
            } else {
                classInfos.get(i).setSelected(false);
            }
        }
    }


    /**
     * 设置展示学生的MyGridView的适配器
     */
    private void initMgv(String classnum) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("ttel", AccountUtils.getAccount(this));
        map.put("num", classnum);
        map.put("platform", "8");
        HttpUtils.post(HttpAdress.CLASSSTUDENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }

                WorkInfo info = null;

                try {
                    info = GsonUtil.jsonToBean(response, WorkInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if (null != info) {
                    if ("1".equals(info.getState())) {
                        //返回成功
                        newDatas = info.getList();
                        if (newDatas != null && newDatas.size() != 0) {
                            //证明该班级有学生数据,显示内容布局同时设置界面数据
                            if (sl_content != null && sl_content.getVisibility() != View.VISIBLE) {
                                sl_content.setVisibility(View.VISIBLE);
                            }
                            if (lv_record != null && lv_record.getVisibility() != View.VISIBLE) {
                                lv_record.setVisibility(View.VISIBLE);
                            }
                            if (tv_msg != null && tv_msg.getVisibility() != View.GONE) {
                                tv_msg.setVisibility(View.GONE);
                            }
                            syncStuData();
                        } else {
                            //没有学生数据,不显示内容布局
                            if (sl_content != null && sl_content.getVisibility() != View.GONE) {
                                sl_content.setVisibility(View.GONE);
                            }
                            //没有学生数据,不显示内容布局
                            if (lv_record != null && lv_record.getVisibility() != View.INVISIBLE) {
                                lv_record.setVisibility(View.INVISIBLE);
                            }
                            if (tv_msg != null && tv_msg.getVisibility() != View.VISIBLE) {
                                tv_msg.setVisibility(View.VISIBLE);
                            }
                        }

                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getState(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getState());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }

    /**
     * 获取服务器数据后同步学生列表的数据
     */
    private void syncStuData() {

        //清空原有的数据集合
        oldDatas.clear();

        // 证明有数据
        if (newDatas.size() <= 4) {
            // 如果少于4个学生不需要显示打开列表的提醒按钮
            llShow.setVisibility(View.GONE);
            tvShow.setText("关闭列表");
            // 小于4个的时候将数据全部添加到oldDatas中
            oldDatas.addAll(newDatas);
        } else {
            // 返回的学生大于4个则显示打开里列表的提醒按钮
            llShow.setVisibility(View.VISIBLE);
            tvShow.setText("打开列表");
            for (int i = 0; i < 4; i++) {
                oldDatas.add(newDatas.get(i));
            }
        }
        // 通知适配器刷新数据
        workSutdentGvAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化展示学生的GridView
     */
    private void initGv() {
        oldDatas = new ArrayList<>();
        workSutdentGvAdapter = new WorkSutdentGvAdapter(this, oldDatas,
                R.layout.teacher_item_gb_students);
        mgv.setAdapter(workSutdentGvAdapter);
    }


    /**
     * 初始化选择相册的九宫格展示
     */
    private void initGvShowPic() {
        mPicPaths = new ArrayList<>();
        adapter = new ShowPicGvAdapter(this, mPicPaths);
        mgvShowWork.setAdapter(adapter);
        mgvShowWork.setOnItemClickListener(this);
    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.rl_back_top) {
            //返回
            finish();
        } else if (id == R.id.lv_record) {
            //跳转到历史练习界面
            Intent intent = new Intent(this, TeacherHistoryHomeWorkActivity.class);
            intent.putExtra("userclass", userclass);
            startActivity(intent);

        } else if (id == R.id.lv_class) {
            //选择班级
            if (isLoadClassCompleted) {
                //弹出选择班级的PopUpWindow
                onChoiceClass();
            } else {
                //没加载完成
                SnackbarUtil.ShortSnackbar(llBaseMain, "正在加载,请稍候", 0);
            }
        } else if (id == R.id.tv_show) {
            //全部打开和关闭的操作
            doOpenOrCloseAction();
        } else if (id == R.id.tv_save) {
            //提交
            doCommitAction();
        }
    }


    /**
     * 提交的处理
     * 1.判断是否选中学生 2.是否点评了上次练习情况 3.是否布置了本次练习
     */
    private void doCommitAction() {
        if (!isSelect()) {
            SnackbarUtil.ShortSnackbar(llMain, "请至少选择一个学生", 0).show();
            return;
        }

        // 上次练习点评
        lastContent = etLastWork.getText().toString().trim();


        // 本次练习
        newContent = etNewWork.getText().toString().trim();
        if (TextUtils.isEmpty(newContent) && (mPicPaths == null || mPicPaths.size() == 0)) {
            SnackbarUtil.ShortSnackbar(llMain, "请布置本次练习或上传图片", 0).show();
            return;
        }

        //图片
        if (mPicPaths == null || mPicPaths.size() == 0) {
            //直接上传
            UIHelper.showDialog(this, "上传中...");
            UploadWork(null, getStudentJson());
        } else {
            //遍历选择的图片进行压缩后进行上传
            //做压缩处理
            UIHelper.showDialog(this, "上传中...");
            List<File> files = new ArrayList<>();
            for (int i = 0; i < mPicPaths.size(); i++) {
                File file = new File(mPicPaths.get(i));
                files.add(file);
            }

            //使用Luban做压缩图片处理.setMaxSize(550).setMaxHeight(1280).setMaxWidth(720)
            Luban.compress(this, files).putGear(Luban.CUSTOM_GEAR).launch(new OnMultiCompressListener() {

                @Override
                public void onStart() {
                    //压缩开始
                }

                @Override
                public void onSuccess(List<File> fileList) {
                    //压缩成功后的回调,上传该集合的文件
                    UploadWork(fileList, getStudentJson());
                }

                @Override
                public void onError(Throwable e) {
                    //压缩错误
                }
            });
        }
    }


    /**
     * 获取选中学生数据
     */
    private String getStudentJson() {

        stuList = new ArrayList<>();

        for (int i = 0; i < newDatas.size(); i++) {
            if (!newDatas.get(i).flag) {
                StudentTel stel = new StudentTel();
                stel.setSttel(newDatas.get(i).getSttel());
                stuList.add(stel);
            }
        }

        //转化json
        String json = GsonUtil.listToJson(stuList);

        return json;
    }

    /**
     * 发布练习
     */
    private void UploadWork(List<File> fileList, String json) {
        Map<String, String> map = new HashMap<>();
        if (fileList == null) {
            map.put("type", "91");
        } else {
            map.put("type", "9");
        }
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");
        map.put("studentids", json);
        map.put("userclass", userclass);
        map.put("content", newContent);
        map.put("comment", lastContent);
        LogUtils.iTag("test", "上传的参数是：" + newContent);
        LogUtils.iTag("test", "acc=" + AccountUtils.getAccount(this) + "&role=" + AccountUtils.getRole(this)
                + "&apptoken=" + AccountUtils.getToken(this) + "platform=7&studentids=" + json + "&userclass=" + userclass + "&content=" + newContent + "&comment=" + lastContent);

        //OkGo的请求
        HttpParams httpParams = new HttpParams();
        if (fileList == null) {
            httpParams.put("type", "91");
        } else {
            httpParams.put("type", "9");
        }
        httpParams.put("acc", AccountUtils.getAccount(this));
        httpParams.put("role", AccountUtils.getRole(this));
        httpParams.put("apptoken", AccountUtils.getToken(this));
        httpParams.put("platform", "8");
        httpParams.put("studentids", json);
        httpParams.put("userclass", userclass);
        httpParams.put("content", newContent);
        httpParams.put("comment", lastContent);

        if (fileList == null) {
            //没有图片
            OkHttpUtils.post().url(HttpAdress.HOMEWORK).params(map).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    UiUtils.Toast("服务器异常,上传失败", false);
                    UIHelper.dismissDialog();
                    LogUtils.iTag("test", e.toString());
                }

                @Override
                public void onResponse(String response, int id) {
                    UIHelper.dismissDialog();

                    UiUtils.Toast("上传成功", false);

                    finish();

                    //跳转到历史练习界面
                    Intent intent = new Intent(TeacherAssignHomeworkActivity.this, TeacherHistoryHomeWorkActivity.class);
                    intent.putExtra("userclass", userclass);
                    startActivity(intent);
                }
            });


            //使用OkGo请求
//            OkGo.<String>post(HttpAdress.HOMEWORK).tag(this)
//                    .params(httpParams)
//                    .execute(new com.lzy.okgo.callback.StringCallback() {
//                        @Override
//                        public void onSuccess(Response<String> response) {
//                            UIHelper.dismissDialog();
//                            UiUtils.Toast("上传成功", false);
//                            finish();
//                        }
//
//                        @Override
//                        public void onError(Response<String> response) {
//                            super.onError(response);
//                            UiUtils.Toast("服务器异常,上传失败", false);
//                            UIHelper.dismissDialog();
//                        }
//                    });


        } else if (fileList != null && fileList.size() != 0) {
            //有图片
            Map<String, File> fileMap = new HashMap<>();
            if (fileList != null && fileList.size() != 0) {
                for (int i = 0; i < fileList.size(); i++) {
                    fileMap.put(System.currentTimeMillis() + i + i + ".jpg", fileList.get(i));
                }
            }

            OkHttpUtils.post().url(HttpAdress.HOMEWORK).params(map).files("picture", fileMap).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    UiUtils.Toast("服务器异常,上传失败", false);
                    CustomDialogManager.dissmiss();
                }

                @Override
                public void onResponse(String response, int id) {
                    UIHelper.dismissDialog();
                    UiUtils.Toast("上传成功", false);
                    finish();
                }
            });
        }
    }

    /**
     * 判断老师是否选中了学生的方法 返回值true表示有选择学生,false表示没有选择学生
     *
     * @return
     */
    private boolean isSelect() {
        boolean res = false;
        if (newDatas != null) {
            for (int i = 0; i < newDatas.size(); i++) {
                if (false == newDatas.get(i).flag) {
                    res = true;
                    break;
                }
            }
        }
        return res;
    }

    /**
     * 展示显示全部学生列表和收拢学生列表的操作
     */
    private void doOpenOrCloseAction() {
        // 点击打开列表
        if ("打开列表".equals(tvShow.getText())) {
            // GridView显示全部学生数据
            oldDatas.clear();
            oldDatas.addAll(newDatas);
            workSutdentGvAdapter.notifyDataSetChanged();
            tvShow.setText("关闭列表");
        } else if ("关闭列表".equals(tvShow.getText())) {
            // GridView只显示4条数据
            oldDatas.clear();
            for (int i = 0; i < 4; i++) {
                oldDatas.add(newDatas.get(i));
            }
            workSutdentGvAdapter.notifyDataSetChanged();
            tvShow.setText("打开列表");
        }
    }


    /**
     * 条目点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        Object itemAdapter = parent.getAdapter();
        if (itemAdapter instanceof ShowPicGvAdapter) {
            if (mPicPaths.size() != 9) {
                if (position == ((ShowPicGvAdapter) itemAdapter).getCount() - 1) {
                    PickChooseManager.startPhotoPickActivity(TeacherAssignHomeworkActivity.this, 9 - mPicPaths.size());
                } else {
                    PickChooseManager.startShowBigActivity(TeacherAssignHomeworkActivity.this, mPicPaths, position);
                }
            } else {
                PickChooseManager.startShowBigActivity(TeacherAssignHomeworkActivity.this, mPicPaths, position);
            }
        }
    }

    /**
     * 请求图库后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                for (int i = 0; i < photos.size(); i++) {
                    mPicPaths.add(photos.get(i));
                }
                //通知适配器刷新
                adapter.notifyDataSetChanged();
            }
        }
    }
}
